//A Kernel is nothing more than a pure static task manager. 
//It holds two lists of tasks: active and paused tasks.
//
//Once Kernel::Execute() is called. It will take over the process
//thread. This is because it will loop ENDLESSLY over all the tasks
//in the active task list. This loop will only terminate if there
//are no more active tasks. 
//
//Tasks will be visited each loop in order of descending priority.
//
//In order to register a task with the Kernel follow these steps:
// 1) Create a new task class derived from Task (task.h)
// 2) Wrap this new task in a CountedPointer object
// 3) Call Kernel::AddTask()
//Note that this will fail if the task is already registered with
//the Kernel.

#ifndef ENGINE_KERNEL_H
#define ENGINE_KERNEL_H

#include <list>
#include <algorithm>

#include <boost/shared_ptr.hpp>

#include "base/result_codes.h"
#include "base/types.h"

#include "engine/result_codes.h"
#include "engine/task.h"

namespace engine
{

class Kernel
{
public:
    static int Execute();  

    static int AddTask(boost::shared_ptr<Task> & aTask);
    static int SuspendTask(boost::shared_ptr<Task> & task);
    static int ResumeTask(boost::shared_ptr<Task> & task);
    static int KillTask(boost::shared_ptr<Task> & task);
    static int KillAllTasks();

    static int ForceShutdown();
    //The Following functions are provided in order to test
    //the functionality of the Kernel
    //
    //NOTE:: They are deprecated and will be removed in future versions
    //Avoid using these in production code.
    static inline int GetActiveTaskCount() {return active_task_list_.size();}
    static inline int GetPausedTaskCount() {return paused_task_list_.size();}
private:
    //This Function is used as a predicate to std::list::remove_if()
    //Determines whether a task may be killed by cheking task::GetCanKill()
    //
    //Side Effect: If the task can be removed, task::Stop() is called 
    static bool CanKillTask(boost::shared_ptr<Task> & task);

    //This Function is used to sort tasks by their priority
    static inline bool CompareTask(const boost::shared_ptr<Task> & first, const boost::shared_ptr<Task> & second) {
        return first->GetPriority() < second->GetPriority();
    }

    static std::list< boost::shared_ptr<Task> > active_task_list_;
    static std::list< boost::shared_ptr<Task> > paused_task_list_;
};

}

#endif //end #ifndef ENGINE_KERNEL_H